from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

# 查看举报列表
def index(request):
    return render(request, 'index.html')

# 提交举报
def upform(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        address = request.POST.get('address')
        phone = request.POST.get('phone')
        title = request.POST.get('title')
        is_public = request.POST.get('is_public')
        email = request.POST.get('email')
        post_code = request.POST.get('post_code')
        qq = request.POST.get('qq')
    return render(request, 'upform.html')


# 上传文件
@csrf_exempt
def upload(request):
    if request.method == "GET":
        return render(request,"upload.html")
    if request.method == "POST":
        # Todo 获取上传文件得处理对象，通过对象获取里面文件名称和内容，
        img = request.FILES.get("file",None)
        if img:
            new_date = datetime.datetime.now().strftime("%Y-%m-%d")
            new_time = time.time()

            # print(img.name) 获取文件名称
            # print(img.chunks) 获取文件内容
            # 创建文件

            save_path = '{}/{}/{}'.format("media",new_date,str(int(new_time))+img.name[img.name.rfind('.'):])
            if not os.path.exists('media/'+new_date):
                os.mkdir('media/'+new_date)
            with open(save_path,'wb') as f:
                for content in img.chunks():
                    f.write(content)
            return JsonResponse({"info":save_path})
        else:
            return JsonResponse({"info": "上传图片不正确"})

def add1(request):
    return render(request, 'addbook.html')

def add2(request):
    return render(request, 'upload.html')


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .models import Complaint
from django.core.files.storage import FileSystemStorage

@require_http_methods(["POST"])
@csrf_exempt
def upload_file(request):
    print("调用了====",request.POST)
    if 'file' not in request.FILES:
        return JsonResponse({'error': 'No file part'}, status=400)

    file = request.FILES['file']
    # 检查文件大小
    max_size = 5 * 1024 * 1024  # 5MB
    if file.size > max_size:
        return JsonResponse({'error': 'File size exceeds 5MB limit'}, status=400)

    # 检查文件格式
    valid_extensions = ['doc','png','jpeg','jpg','gif','bmp']
    file_extension = file.name.split('.')[-1].lower()
    if file_extension not in valid_extensions:
        return JsonResponse({'error': 'Invalid file format. Only .doc is allowed'}, status=400)

    fs = FileSystemStorage()
    filename = fs.save(file.name, file)
    uploaded_file_url = fs.url(filename)

    # 在这里，你可以将文件信息保存到数据库或其他地方
    # 例如，创建一个Complaint模型实例并保存
    # 创建并保存FileUpload模型实例
    file_upload = Complaint(
        name=request.POST.get('name'),
        # name = "随便起的名字",
        address = "随便填一个地址",
        attachment=filename,
        complaint_type=1,
        title="没啥事",
        phone="12345",
        content="啥事也没有"
    )
    print("上传的是",file_upload)
    file_upload.save()


    return JsonResponse({'url': uploaded_file_url})